<template>
  <div class="post_comment">
    <div class="comment">
      <!-- 评论标题 -->
      <h4>评论区</h4>

      <!-- 评分 -->
      <el-form :model="form2">
        <el-form-item label="总体评价:" :label-width="formLabelWidth">
          <el-rate v-model="form2.score.all" show-text></el-rate>
        </el-form-item>
        <el-form-item label="设施:" :label-width="formLabelWidth">
          <el-rate v-model="form2.score.fancility" show-text></el-rate>
        </el-form-item>
        <el-form-item label="服务:" :label-width="formLabelWidth">
          <el-rate v-model="form2.score.service" show-text></el-rate>
        </el-form-item>
        <el-form-item label="位置:" :label-width="formLabelWidth">
          <el-rate v-model="form2.score.location" show-text></el-rate>
        </el-form-item>
      </el-form>
      <!-- 显示评论回复的用户 -->
      <div class="replycon" v-if="replyuser.trim()!=''">
        <span class="replyuser">
          回复 @{{replyuser}}
          <i class="el-tag__close el-icon-close" @click="delReplyUser"></i>
        </span>
      </div>
      <!-- 评论框 -->
      <el-input type="textarea" ref="commentInput" v-model="form.content" placeholder="请输入你对该酒店的评价"></el-input>
      <!-- 评论图片上传 -->
      <div class="comment_picture">
        <!-- :on-preview="handlePictureCardPreview" -->
        <!-- upload接口需要files参数，因此需要绑定name -->
        <!-- beforeAvatarUpload限制文件上传大小 -->
        <el-upload
          action="http://157.122.54.189:9095/upload"
          name="files"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          :before-upload="beforeAvatarUpload"
          :on-exceed="handleExceed"
          :limit="5"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
        <div class="btn" @click="sendComment">提交</div>
      </div>
      <!-- 评论内容 -->
      <div class="comment_content" v-for="(item, index) in commentList" :key="index">
        <div class="comment_writer">
          <div class="writer">
            <img src="http://157.122.54.189:9095/assets/images/avatar.jpg" alt />
            <div class="admin">{{item.account.nickname}}</div>
            <div class="date">{{item.updated_at | formatTime}}</div>
            <!-- <div class="time">{{item.account.updated_at | formatTime}}</div> -->
          </div>
          <div class="floor">{{item.level}}楼</div>
        </div>
        <!-- 如果follow有数据我才显示 并且传值，否则不显示 -->
        <postSonComment
          @sendReply="childrenHandlerReply"
          :parentComment="item.parent"
          v-if="item.parent"
        />
        <div class="post_comment_content">
          <div class="content">{{item.content}}</div>
          <div class="img" v-if="item.pics.length>0">
            <span class="imgItem" v-for="(v,i) of item.pics" :key="i">
              <img :src="$axios.defaults.baseURL+v.url" alt />
            </span>
          </div>
          <!-- 将回复id传入 -->
          <div class="clearfix">
            <span class="button" @click="handlerReply(item.id,item.account.nickname)">回复</span>
          </div>
        </div>
      </div>

      <!-- 没有评论内容 -->
      <div v-show="commentList.length==0" class="comment_null">暂无评论，赶紧抢占沙发！</div>
    </div>
  </div>
</template>

<script>
// import postSonComment from "./parentComment";
import moment from "moment";
import postSonComment from "@/components/hotel/details/myFloor";
export default {
  directives: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
    },
  },
  filters: {
    // 时间戳过滤器
    formatTime(val) {
      let res = moment(val).format("YYYY-MM-DD hh:mm:ss");
      return res;
    },
  },
  // 接收父组件传过来的页码和当前页
  props: ["currentPage", "pageSize"],
  components: {
    postSonComment,
  },

  data() {
    return {
      form2: {
        score: {
          all: null, //总体评分
          fancility: null, //设施评分
          service: null, //服务评分
          location: null, // 位置评分
        },
        content: null, // 内容
        pics: [], // 图片数据
      },
      formLabelWidth: "120px",
      // headers: {
      //   Authorization: "Bearer " + token,
      //   "Content-Type": "application/json",
      // },
      dialogImageUrl: "",
      dialogVisible: false,
      // 提交评论的数据
      form: {
        //回复内容
        content: "",
        pics: [],
        //文章
        post: "",
        // 回复id
        follow: "",
      },
      commentList: [],
      replyuser: "",
      pagenations: {
        currentPage: "",
        pageSize: "",
      },
      fileList: [],
      commentTotal: "",
    };
  },
  // 监听器监听父组件传过来的当前页和页数
  watch: {
    currentPage(val) {
      console.log("评论组件监听的当前页：" + val + ",再次发送请求");
      this.pagenations.currentPage = val;
      this.queryComment(
        this.pagenations.currentPage,
        this.pagenations.pageSize
      );
    },
    pageSize(val) {
      console.log("评论组件监听的显示页数：" + val + ",再次发送请求");
      // 重置为第一页
      this.pagenations.currentPage = 1;
      this.pagenations.pageSize = val;
      this.$emit("getPages", this.pagenations.currentPage);
      this.queryComment(
        this.pagenations.currentPage,
        this.pagenations.pageSize
      );
      // this.$axios({
      //   url: "/posts",
      //   params: this.$route.query,
      // }).then((res) => {
      //   const { data } = res.data;
      //   this.postDetail = data;
      //   // console.log(this.postDetail);
      // });
    },
  },
  mounted() {
    // 进到页面判断缓存里面是否有值，回显到评论
    let commentForm = localStorage.getItem("curComments");
    if (commentForm) {
      let { content, post, follow, repUser } = JSON.parse(commentForm);
      this.form.content = content;
      this.form.post = post;
      this.form.follow = follow;
      this.replyuser = repUser;
      localStorage.removeItem("curComments");
    }
    // 1.进到页面获取文章id
    this.form.post = this.$route.query.id;
    // 2.获取父组件传递过来的页码
    this.pagenations.pageSize = this.pageSize;
    this.pagenations.currentPage = this.currentPage;
    console.log(this.pagenations.pageSize, this.pagenations.currentPage);
    // 3.请求文章的所有评论
    this.queryComment(this.pagenations.currentPage, this.pagenations.pageSize);
  },
  created() {
    // console.log(this.$route.query);
  },
  methods: {
    // 移除图片方法
    handleRemove(file, fileList) {
      console.log("---执行handleRemove");
      this.form.pics = fileList;
      console.log("现在pics为：");
      console.log(this.form.pics);
    },
    // 图片预览方法
    handlePictureCardPreview(file) {
      console.log("---执行handlePictureCardPreview");
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
    },
    // 图片上传成功时的方法
    handleSuccess(res, file, fileList) {
      this.form.pics = fileList;
      console.log("上传封面成功 this.form.pics:");
      console.log(this.form.pics);
    },
    // 限制图片上传大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      console.log("handlePictureCardPreview---------------");
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能添加5张图片哦~`);
    },
    // 获取文章评论请求
    queryComment(currentPage, pageSize) {
      let _start = (currentPage - 1) * pageSize;
      let _limit = pageSize;
      console.log(
        "分页参数的_start:" +
          _start +
          "---_limit:" +
          _limit +
          "当前文章id:" +
          this.form.post
      );

      let data = { post: this.form.post, _limit: _limit, _start: _start };

      // _limit 条数，_start开始数据
      this.$axios({
        url: "/posts/comments",
        params: data,
      }).then((res) => {
        // console.log(res.data);
        this.commentList = res.data.data;
        // 将分页总数传给父组件
        this.$emit("getTotal", res.data.total);
        console.log("---获取的文章评论数据：---");
        console.log(this.commentList);
      });
    },
    // 发送评论请求
    sendComment() {
      console.log(`执行sendComment提交评论`);

      this.form.pics = this.form.pics.map((item) => {
        if (item && item.response) {
          return item.response[0];
        }
      });
      console.log(this.form);
      const { content, pics, post, follow } = this.form;

      // 发送请求之前进行校验 是否为空
      if (content.trim() == "") {
        this.$message({
          message: "评论内容不能为空",
          type: "warning",
        });
        this.fileList = [];
        return;
      }

      //通过Vuex中state获取用户登录信息：token值
      let token = this.$store.state.user.userInfo.token;

      if (!token) {
        this.$message({
          message: "请先登录",
          type: "warning",
        });
        let { content, post, follow } = this.form;
        let repUser = this.replyuser;
        console.log("将评论内容,回复人员id,post文章id 存入本地缓存：");
        localStorage.setItem(
          "curComments",
          JSON.stringify({ content, post, follow, repUser })
        );
        this.$router.push({ path: `/user/login?comment=true&id=4` });
      } else {
        this.$axios({
          url: "/comments",
          method: "post",
          headers: {
            Authorization: `Bearer ${token}`,
          },
          data: { content, pics, post, follow },
        }).then((res) => {
          console.log(res);
          if (res.status == 200) {
            this.$message({
              message: "评论成功！",
              type: "success",
            });
            console.log(`重新渲染评论数据：`);
            // 重新渲染评论页面
            this.queryComment(
              this.pagenations.currentPage,
              this.pagenations.pageSize
            );
            this.form.content = "";
            this.form.pics = [];
            this.follow = "";
            this.fileList = [];
            this.replyuser = "";
            this.form2.score.all = "";
            this.form2.score.fancility = "";
            this.form2.score.service = "";
            this.form2.score.location = "";
          }
        });
      }
    },
    // 点击回复用户
    handlerReply(repid, nickname) {
      this.$refs.commentInput.focus();

      console.log("回复的follow-id：" + repid, "用户：" + nickname);
      this.replyuser = nickname;
      this.form.follow = repid;
    },
    childrenHandlerReply(repObj) {
      this.$refs.commentInput.focus();
      console.log(
        "回复的follow-id：" + repObj.repid,
        "用户：" + repObj.nickname
      );
      this.replyuser = repObj.nickname;
      this.form.follow = repObj.repid;
    },
    // 删除回复用户
    delReplyUser() {
      // 清除恢复用户和回复id
      this.replyuser = "";
      this.form.follow = "";
    },
  },
};
</script>

<style lang="less" scoped>
// 图片组件大小样式
/deep/ .el-upload-list__item {
  width: 100px;
  height: 100px;
  overflow: hidden;
}

/deep/ .el-form {
  text-align: left;

  .el-form-item__label {
    text-align: left;
    line-height: 18px;
  }
}
.post_comment {
  .comment {
    h4 {
      color: #fff;
      padding-left: 10px;
      line-height: 35px;
      border-radius: 5px;
      background: orange;
    }
    .replycon {
      margin-bottom: 5px;
      .replyuser {
        display: inline-block;
        background-color: rgba(144, 147, 153, 0.1);
        border-color: rgba(144, 147, 153, 0.2);
        color: #909399;
        padding: 0 10px;
        height: 32px;
        line-height: 32px;
        font-size: 12px;
        border-radius: 4px;
        box-sizing: border-box;
        border: 1px solid rgba(64, 158, 255, 0.2);
        white-space: nowrap;
        .el-icon-close {
          cursor: pointer;
          width: 15px;
          height: 15px;
          &:hover {
            display: inline-block;
            border-radius: 50%;
            border: 50%;
            background: #909399;
            line-height: 15px;
            text-align: center;
            color: #fff;
          }
        }
      }
    }

    // 评论标题
    h4 {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 20px;
    }
    // 评论框
    /deep/ .el-textarea__inner {
      resize: none;
      height: 100px;
      width: 100%;
      border-radius: 5px;
      padding: 5px 15px;
      margin-bottom: 10px;
    }
    // 评论图片上传
    .comment_picture {
      display: flex;
      justify-content: space-between;
      margin-bottom: 30px;
      /deep/ .el-upload {
        width: 100px;
        height: 100px;
        line-height: 100px;
      }
      .btn {
        cursor: pointer;
        width: 56px;
        height: 28px;
        background-color: #409eff;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        font-size: 14px;
        border-radius: 5px;
      }
    }

    // 评论内容
    .comment_content {
      // 鼠标移入显示回复按钮
      &:hover .post_comment_content .button {
        visibility: visible;
      }

      border: 1px solid #e3e3e3;
      margin-bottom: 20px;
      padding: 20px 20px 5px;
      .comment_writer {
        height: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        font-size: 12px;
        .writer {
          height: 16px;
          display: flex;
          align-items: center;
          color: #666;
          img {
            width: 16px;
            height: 16px;
            object-fit: cover;
            margin-right: 7px;
          }
          .date {
            color: #999;
            margin: 0 5px;
          }
          .time {
            color: #999;
          }
        }
      }
      .post_comment_content {
        overflow: hidden;
        padding-left: 30px;
        .content {
          padding-left: 5px;
        }
        .img {
          width: 103px;
          height: 103px;
          display: flex;
          // align-items: center;
          // justify-content: center;
          margin-top: 10px;
          .imgItem {
            border: 1px dashed #dddddd;
            border-radius: 5px;
            padding: 5px;
            margin-left: 5px;
          }
          img {
            width: 90px;
            height: 90px;
            object-fit: cover;
          }
        }
        .button {
          cursor: pointer;
          color: #1e50b5;
          height: 20px;
          display: flex;
          align-items: center;
          // justify-content: flex-end;
          float: right;
          font-size: 12px;
          visibility: hidden;
        }
      }
    }

    // 没有评论内容
    .comment_null {
      width: 100%;
      height: 80px;
      border: 1px dashed #dddddd;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      font-size: 14px;
      color: #999999;
    }
  }
}
</style>